package cn.bytengine.stem.module;

import cn.bytengine.stem.contexts.Context;
import cn.bytengine.stem.contexts.Setter;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.OrderComparator;

import java.util.List;

public class SpringModuleStarter implements ApplicationRunner {
    private List<ModuleFactory<? extends Module>> moduleFactoryList;
    private String applicationName;
    private Context context;

    public SpringModuleStarter(String applicationName,
                               List<ModuleFactory<? extends Module>> moduleFactoryList) {
        this.applicationName = applicationName;
        OrderComparator.sort(moduleFactoryList);
        this.moduleFactoryList = moduleFactoryList;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        context = buildAppContext();
        run(context, moduleFactoryList);
    }

    protected Context buildAppContext() {
        Context context = Context.core();
        initContext(context);
        return context;
    }

    protected void initContext(Setter<? extends Setter<?>> accessor) {
        accessor
                .set("application.name", getApplicationName());
    }

    protected void run(Context context, List<ModuleFactory<? extends Module>> moduleFactoryList) {
        moduleFactoryList.forEach(moduleFactory -> this.initModule(context, moduleFactory));
    }

    protected void initModule(Context context, ModuleFactory<? extends Module> moduleFactory) {
        moduleFactory.createModule().init(context, moduleFactory.getConfig());
    }

    protected String getApplicationName() {
        return applicationName;
    }
}
